package com.yhp.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //将所有请求进行字符转码
        request.setCharacterEncoding("utf-8");
        //防止用户未在登陆时访问
        String requestURI = request.getRequestURI();
        //获取session
        Object username = request.getSession().getAttribute("username");
//        if ("/loginRequest".equals(requestURI) || "/login.jsp".equals(requestURI)) {
//            filterChain.doFilter(servletRequest, servletResponse);
//            return;
//        }
        if (requestURI.endsWith("/") && username == null){
            // 跳转到登陆页面
            response.sendRedirect("/login.jsp");
        } else {
            // 已经登陆,继续此次请求
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
